<template>
	<div class="container">
		<h1 style="text-align: center;font-weight: bold;">{{ route.query.type==1?"周转料":"机械" }}出场确认</h1>
		<a-form ref="formRef" :model="formState" layout="vertical">
			<a-row :gutter="20">
				<a-col :span="24">
					<h3>计划信息</h3>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择项目" name="project_id" :rules="{required:true, message:'请选择项目'}">
						<a-select v-model:value="formState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划名称" name="name" :rules="{required:true, message:'请输入计划名称'}">
						<a-input v-model:value="formState.name" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划编号" name="code" :rules="{required:true, message:'请输入计划编号'}">
						<a-input v-model:value="formState.code" />
					</a-form-item>
				</a-col>
				<!--
				<a-col :span="12">
					<a-form-item label="计划制定人" name="user_ids" :rules="{required:true, message:'请选择计划制定人'}">
						<a-select v-model:value="formState.user_ids" show-search="true" mode="multiple" placeholder="请选择计划制定人" :options="userOptions" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				
				<a-col :span="12">
					<a-form-item label="计划日期" name="plan_date" :rules="{required:true, message:'请选择计划日期'}">
						<a-date-picker v-model:value="formState.plan_date" style="width:100%" />
					</a-form-item>
				</a-col>-->

				<a-col :span="24">
					<h1 style="text-align: center;font-weight: bold;">物资计划清单</h1>
					<a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :data-source="formState.materials" :scroll="tableScroll" :columns="planMaterialColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{required:true, message:'请选择材料名称'}">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" disabled :show-search="true" placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id)=>changeMaterial(id, record)">
										<template #title="{label}">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{required:true, message:'请选择规格'}">
									<a-select v-model:value="formState.materials[record.key].id" disabled :show-search="true" option-filter-prop="model" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{value:'id', label:'model'}" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{required:true, message:'请选择计量单位'}">
									<a-select v-model:value="formState.materials[record.key].unit" disabled :show-search="true" placeholder="请选择" :options="unitOptions" :field-names="{value:'name'}" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{required:true, message:'请输入数量'}">
									<a-input v-model:value="formState.materials[index]['quantity']" placeholder="请输入数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'gonghao'">
								<a-form-item :name="['materials', index, 'gonghao_'+column.extra]">
									<a-input v-model:value="formState.materials[index]['gonghao_'+column.extra]" placeholder="请输入数量" @change="setQty(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']" :rules="{required:true, message:'请输入使用时长'}">
									<a-input v-model:value="formState.materials[index]['use_time']" placeholder="请输入使用时长" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'time_unit'">
								<a-form-item :name="['materials', index, 'time_unit']" :rules="{required:true, message:'请选择时长单位'}">
									<a-select v-model:value="formState.materials[record.key].time_unit" :show-search="true" placeholder="请选择时长单位" :options="timeunitOptions" :field-names="{value:'name'}" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'price'">
								<a-form-item :name="['materials', index, 'price']" :rules="{required:true, message:'请输入单价'}">
									<a-input v-model:value="formState.materials[index]['price']" placeholder="请输入单价" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'add_time'">
								<a-form-item :name="['materials', index, 'add_time']">
									<a-date-picker v-model:value="formState.materials[index]['add_time']" show-time placeholder="选择时间" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-button type="primary" @click="chuchang(record)">
										<copy-outlined />出场确认
									</a-button>
								</a-space>
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-popconfirm title="确定要现在出场吗？" ok-text="是" cancel-text="否" @confirm="chuchang(record)">
							<a-button type="primary" danger>
								<right-outlined />出场确认
							</a-button>
						</a-popconfirm>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from "vue";
import { RightOutlined } from "@ant-design/icons-vue";
import dayjs from "dayjs";

import { post, listToTree } from "../utils";

import { useRoute } from "vue-router";
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const timeunitOptions = ref([]);
const formState = ref({ parent_id: route.query.parent_id || 0, materials: [] });
const projectOptions = ref([]);
const userOptions = ref([]);
const oldMaterials = ref([]);
const jcForm = ref([]);
post("dictionary", { root_code: "MATERIAL_TIMEUNIT" }).then(data => {
	timeunitOptions.value = data;
});
jcForm.value.start_time = dayjs();
onMounted(() => {
	const { parent_id } = formState.value;
	if (parent_id) {
		post("plan/info", { id: parent_id }).then(data => {
			const { name, code, project_id } = data;
			formState.value = {
				...formState.value,
				name,
				code,
				project_id
			};
			//构建工号
			post("department/info", { id: data.project_id }).then(d => {
				//获取工号
				pointData.value = d.pointData;
			});
		});
		//原计划物资清单
		post("plan/hebing", { id: parent_id }).then(data => {
			oldMaterials.value = data.map((d, i) => {
				d.key = i;
				return d;
			});
		});
	} else if (id.value) {
		post("plan/info", { id: id.value }).then(data => {
			//data.user_ids = data.users.map(d => d.id) || [];
			data.user_id = data.opr_user.id;
			if (data.plan_date) data.plan_date = dayjs(data.plan_date);

			data.materials = data.materials.map((d, i) => {
				d.key = i;

				const { unit, quantity } = d.PlanMaterial;
				d.unit = unit;
				d.quantity = quantity;
				d.price = "";
				d.use_time = "";
				d.time_unit = "";
				return d;
			});
			//构建工号
			post("department/info", { id: data.project_id }).then(d => {
				//获取工号
				pointData.value = d.pointData;
			});
			formState.value = data;
		});
	}

	post("user").then(({ data }) => {
		userOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.fullname || d.username
			};
		});
	});
	//projectOptions
	post("department/projects?type=3").then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
});
const pointData = ref([]);
const hasPoint = ref(true);
const changeProject = value => {
	const project_id = value;
	post("department/info", { id: project_id }).then(data => {
		//自动生成计划编码
		if (data.name) {
			let py_name = "";
			const name = data.company_name + "-" + data.name;
			post("util/pinyin", { value: name }).then(res => {
				res.value.forEach(d => {
					py_name += d.toUpperCase();
				});
				//获取计划最大ID
				let maxid = 0;
				post("plan/maxid", { project_id: project_id }).then(max => {
					maxid = parseInt(max) + 1;
					formState.value.code = "ZTJGSJ-" + py_name + "-" + maxid;
				});
			});
		}
		//获取工号
		pointData.value = data.pointData;
		if (data.pointData.length === 0) {
			hasPoint.value = false;
			proxy.$message.error("只能选择有工号的项目");
		}
	});
};

const goods = ref({ selectedRowKeys: [] });
const onSelectChange = selectedRowKeys => {
	goods.value.selectedRowKeys = selectedRowKeys;
};

const chuchang = record => {
	const datas = [];

	if (record && record.quantity > 0) {
		//单个进场确认
		const data = {};
		data.type = 2;
		data.material_id = formState.value.materials[record.key].id;
		data.qty = record.quantity;
		data.plan_id = id.value;
		data.use_time = record.use_time;
		data.time_unit = record.time_unit;
		data.price = record.price;
		datas.push(data);
	} else {
		//批量进场确认
		if (goods.value.selectedRowKeys.length === 0) {
			proxy.$message.error("请先选择物资");
			return;
		}
		goods.value.selectedRowKeys.map(d => {
			const data = {};
			data.type = 2;
			data.material_id = formState.value.materials[d]["id"];
			data.qty = formState.value.materials[d]["quantity"];
			data.plan_id = id.value;
			data.use_time = formState.value.materials[d]["use_time"];
			data.time_unit = formState.value.materials[d]["time_unit"];
			data.price = formState.value.materials[d]["price"];
			datas.push(data);
		});
	}
	const res = JSON.stringify(datas);
	post("accept/savelog", { data: res })
		.then(() => {
			proxy.$message.success("出场确认成功");
		})
		.catch(err => {
			proxy.$message.error(err);
		});
};

const setQty = value => {
	formState.value.materials.forEach(d => {
		let quantity = 0;
		pointData.value.forEach(p => {
			if (Number.parseFloat(d["gonghao_" + p.id]) >= 0) {
				quantity = Number.parseFloat(quantity) + Number.parseFloat(d["gonghao_" + p.id]);
				quantity = quantity.toFixed(2);
			}
		});
		d.quantity = quantity;
	});
};
const { proxy } = getCurrentInstance();
const formRef = ref();

const planMaterialColumns = computed(() => {
	const planMaterialColumns = [
		{
			title: "材料名称",
			dataIndex: "name",
			width: 150,
			extra: 0
		},
		{
			title: "材料规格",
			dataIndex: "model",
			width: 150,
			extra: 0
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "数量",
			dataIndex: "quantity",
			width: 120,
			extra: 0,
			align: "center"
		},
		{
			title: "实际使用时长",
			dataIndex: "use_time",
			width: 120,
			extra: 0,
			align: "center"
		},
		{
			title: "时长单位",
			dataIndex: "time_unit",
			width: 120,
			extra: 0,
			align: "center"
		},
		{
			title: "结算单价",
			dataIndex: "price",
			width: 120,
			extra: 0,
			align: "center"
		}
	];
	pointData.value.forEach((p, i) => {
		planMaterialColumns.push({
			title: p.name,
			dataIndex: "gonghao",
			extra: p.id,
			align: "center",
			width: 120
		});
	});
	planMaterialColumns.push({
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	});

	return planMaterialColumns;
});

const unitOptions = ref([]);
post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});

const materialOptions = ref([]);

post("dictionary", { root_code: "MATERIAL_CATEGORY" }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);

	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value = (() => {
			const array = [];
			data.forEach(d => {
				if (!array[d.source_id]) array[d.source_id] = [];

				if (d.attr) d.model = `${d.model}（${d.attr}）`;

				array[d.source_id].push(d);
			});

			return array;
		})(data);
	});
});

const materialModelOptions = ref({});

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;

	if (!id) return;

	post("material", { source_id: id, page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}
:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-select-disabled.ant-select-multiple .ant-select-selection-item) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-picker-input > input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
}
:deep(.ant-picker.ant-picker-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
</style>
